﻿using System.Linq;
using K9Nano.AspNetCore.Api;
using K9Nano.AspNetCore.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace K9Nano.AspNetCore.Filters
{
    public class K9ActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Canceled || context.Exception != null)
            {
                return;
            }

            switch (context.Result)
            {
                case JsonResult jsonResult:
                    if (!(jsonResult.Value is ApiResponse))
                    {
                        jsonResult.Value = ApiResponse.FromDto(jsonResult.Value);
                    }
                    return;
                case BadRequestResult _:
                case OkResult _:
                case FileResult _:
                case StatusCodeResult _:
                case BadRequestObjectResult _:
                    // do nothing
                    return;
                case ObjectResult objectResult:
                    if (objectResult.Value is ApiResponse) break;
                    context.Result = new JsonResult(objectResult.Value == null
                        ? new ApiResponse()
                        : ApiResponse.FromDto(objectResult.Value));
                    break;
                case EmptyResult _:
                    context.Result = new JsonResult(new ApiResponse());
                    return;
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                if (context.Filters.OfType<ApiControllerAttribute>().Any())
                {
                    var error = context.ModelState.GetErrors();
                    context.Result = new JsonResult(new ApiResponse(400, "参数非法", error))
                    {
                        StatusCode = 400
                    };
                }
            }
        }
    }
}